from django.shortcuts import render,reverse,redirect
from django.http import JsonResponse, HttpResponse, HttpResponseRedirect
from django.conf import settings
from common import utils
from common.py_redis import PyRedis
import time
import hashlib
from django.views.decorators.cache import cache_page
from django.core.cache import cache
from index.models import VisitInfo
from django.db.models import F,Q,Sum
from django.views import View
from notes import models as note_models
import logging

LOGApi = logging.getLogger('api')


# Create your views here.
# @cache_page(100)
def index(request):
    if request.method == 'GET':
        notes_list = note_models.Note.objects.filter(is_pub=0).order_by('-likes','-collections','-reading')[:10]
        data = {
            "notes":notes_list,
        }
        return render(request,'index.html',data)

class NotFoundView(View):
    def get(self, request):
        if request.method == 'GET':
            forbid_tip = '404'
            return render(request,'error/forbid.html',{"forbid_tip":forbid_tip})

@utils.check_login
def logout(request):
    if request.method == 'GET':
        url = reverse('index')
        resp = HttpResponseRedirect(url)
        resp.delete_cookie('token')
        resp.delete_cookie('uid')
        resp.delete_cookie('figureurl')
        resp.delete_cookie('qq')
        return resp

def varify_code_view(request):
    try:
        code,buf = utils.varify_code()
        resp = HttpResponse(buf.getvalue(), content_type='image/jpg')
        t = time.time()
        key = str(t) + settings.SECRET_KEY
        key = utils.get_md5(key)
        py_redis = PyRedis()
        result = py_redis.set(key,code.lower(),settings.REDIS_EXPIRATION_TIME)
        result = py_redis.get(key)
        if result:
            resp.set_cookie('code_key',key,300)
            return resp
        else:
            return HttpResponse("code error")
    except Exception as e:
        return HttpResponse(str(e))

class  NavIndex(View):
    '''
    导航页面
    :param param1(int):
    :param param2(int):
    return:
    '''
    def get(self, request):
        return render(request, 'nav/index.html')

class  NavCommon(View):
    '''
    导航页面
    :param param1(int):
    :param param2(int):
    return:
    '''
    def get(self, request):
        return render(request, 'nav/common.html')

class  NavDevelop(View):
    '''
    导航页面
    :param param1(int):
    :param param2(int):
    return:
    '''
    def get(self, request):
        return render(request, 'nav/develop.html')

class  NavTools(View):
    '''
    导航页面
    :param param1(int):
    :param param2(int):
    return:
    '''
    def get(self, request):
        return render(request, 'nav/tools.html')









